//
//  UIButton+UIButton_bgColor.m
//  Xspcf
//
//  Created by sunshine on 16/7/21.
//  Copyright © 2016年 sun. All rights reserved.
//

#import "UIButtonSun.h"
#import <objc/runtime.h>
@implementation UIButton (Sun)
static char overViewKey;

- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
    [self setBackgroundImage:[self imageWithColor:backgroundColor] forState:state];
}
- (void)verticalImageAndTitle:(float)sapce{
    CGSize imageSize = self.imageView.image.size;
    CGSize textSize = [self.titleLabel.text sizeWithAttributes:@{NSFontAttributeName : self.titleLabel.font}];
    self.imageEdgeInsets = UIEdgeInsetsMake(-textSize.height - 5, 0.0, 0.0, -textSize.width);
    self.titleEdgeInsets = UIEdgeInsetsMake(sapce?sapce:imageSize.height + 5, -imageSize.width, 0, 0);
}
- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
- (void)doclick:(ButtonClickCallback)callBack {
    [self handleClickEvent:UIControlEventTouchUpInside callBack:callBack];
}

- (void)handleClickEvent:(UIControlEvents)aEvent
                callBack:(ButtonClickCallback)callBack;
{
    objc_setAssociatedObject(self, &overViewKey, callBack, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(buttonClick) forControlEvents:aEvent];
}

- (void)buttonClick {
    ButtonClickCallback callBack = objc_getAssociatedObject(self, &overViewKey);
    if (callBack!= nil)
    {
        callBack();
    }
}
@end
